// FreeSWITCH 布局工具函数

/**
 * 将像素坐标转换为 FreeSWITCH 布局中的相对坐标 (0-1)
 */
export function pixelToRelative(pixel: number, total: number): number {
  return Math.round((pixel / total) * 100) / 100
}

/**
 * 将相对坐标转换为像素坐标
 */
export function relativeToPixel(relative: number, total: number): number {
  return Math.round(relative * total)
}

/**
 * 生成 FreeSWITCH 布局 XML 配置
 */
export function generateLayoutXml(
  layoutName: string,
  elements: Array<{
    id: string
    x: number
    y: number
    width: number
    height: number
    zIndex: number
    label: string
  }>,
  canvasSize: { width: number; height: number },
): string {
  let xml = `<configuration name="conference_layouts.conf" description="Conference Layout">
  <layouts>
    <layout name="${layoutName}">
`

  elements
    .sort((a, b) => a.zIndex - b.zIndex)
    .forEach((el, index) => {
      const x = pixelToRelative(el.x, canvasSize.width)
      const y = pixelToRelative(el.y, canvasSize.height)
      const width = pixelToRelative(el.width, canvasSize.width)
      const height = pixelToRelative(el.height, canvasSize.height)

      xml += `      <image x="${x}" y="${y}" scale="${width}x${height}" floor="${index}" overlap="true" reservation_id="${
        index + 1
      }" zoom="${index === 0 ? "0" : "0"}"/>\n`
    })

  xml += `    </layout>
  </layouts>
</configuration>`

  return xml
}

/**
 * 解析 FreeSWITCH 布局 XML 配置
 */
export function parseLayoutXml(
  xml: string,
  canvasSize: { width: number; height: number },
): {
  layoutName: string
  elements: Array<{
    id: string
    x: number
    y: number
    width: number
    height: number
    zIndex: number
    label: string
  }>
} {
  const layoutNameMatch = xml.match(/<layout name="([^"]+)">/)
  const layoutName = layoutNameMatch ? layoutNameMatch[1] : "未命名布局"

  const imageRegex =
    /<image x="([^"]+)" y="([^"]+)" scale="([^"x]+)x([^"]+)" floor="([^"]+)" overlap="([^"]+)" reservation_id="([^"]+)" zoom="([^"]+)"\/>/g

  const elements = []
  let match

  while ((match = imageRegex.exec(xml)) !== null) {
    const [, x, y, width, height, floor, , reservationId] = match

    elements.push({
      id: `element-${floor}`,
      x: relativeToPixel(Number.parseFloat(x), canvasSize.width),
      y: relativeToPixel(Number.parseFloat(y), canvasSize.height),
      width: relativeToPixel(Number.parseFloat(width), canvasSize.width),
      height: relativeToPixel(Number.parseFloat(height), canvasSize.height),
      zIndex: Number.parseInt(floor),
      label: `参与者 ${reservationId}`,
    })
  }

  return {
    layoutName,
    elements,
  }
}
